﻿using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;
using ComponentArt.Web.UI;
using System.Collections.Generic;

namespace Common
{
    public static class Utilities
    {
        public static string GetGalleryPath()
        {
            try
            {
                return PhysicalApplicationPath() + "//Gallery//";
            }
            catch { return ""; }
        }

        public static string ImagesUrl()
        {
            try
            {
                return ApplicationPath + "Images/";
            }
            catch { return ""; }
        }

        public static string ImagesUrlAdmin()
        {
            try
            {
                return ApplicationPath + "Admin/Images/";
            }
            catch { return ""; }
        }

        public static string GetEditor()
        {
            try
            {
                return ApplicationPath + "Admin/tiny_mce/tiny_mce.js";
            }
            catch { return ""; }
        }

        public static string UcControllAdmin()
        {
            try
            {
                return ApplicationPath + "Admin/ucControl/ControlConfig/";
            }
            catch { return ""; }
        }

        public static string ImagesUrlWebMaster()
        {
            try
            {
                return ApplicationPath + "WebMaster/Images/";
            }
            catch { return ""; }
        }


        public static string UrlJavaScript()
        {
            try
            {
                return ApplicationPath;
            }
            catch { return ""; }
        }


        public static string FullApplicationPath
        {
            get
            {
                return HttpContext.Current.Request.Url.AbsoluteUri.Replace(
                   HttpContext.Current.Request.Url.PathAndQuery, "") + ApplicationPath;
            }
        }

        public static string ApplicationPath
        {
            get
            {
                string url = HttpContext.Current.Request.ApplicationPath;
                if (url.EndsWith("/"))
                    return url;
                else
                    return url + "/";
            }
        }

        /// <summary>
        /// Lấy đường dẫn vật lý
        /// </summary>
        /// <returns></returns>
        public static string PhysicalApplicationPath()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }

        public static int GetIntFromQueryString(string key)
        {
            int returnValue = -1;
            string queryStringValue;

            queryStringValue = HttpContext.Current.Request.QueryString[key];

            if (queryStringValue == null)
                return returnValue;

            try
            {

                if (queryStringValue.IndexOf("#") > 0)
                    queryStringValue = queryStringValue.Substring(0, queryStringValue.IndexOf("#"));

                returnValue = Convert.ToInt32(queryStringValue);
            }
            catch { }

            return returnValue;

        }

        public static string GetStringFromQueryString(string key)
        {
            string returnValue = "";
            string queryStringValue;

            queryStringValue = HttpContext.Current.Request.QueryString[key];


            if (queryStringValue == null)
                return returnValue;

            try
            {

                if (queryStringValue.IndexOf("#") > 0)
                    queryStringValue = queryStringValue.Substring(0, queryStringValue.IndexOf("#"));

                returnValue = Convert.ToString(queryStringValue);
            }
            catch { }

            return returnValue;
        }

        public static Int32 ConvertToInt32(object obj)
        {
            try
            {
                return Convert.ToInt32(obj);
            }
            catch { return -1; }
        }

        public static Double ConvertToDouble(object obj)
        {
            try
            {
                return Convert.ToDouble(obj);
            }
            catch { return -1; }
        }

        /// <summary>
        /// Kiểm tra chuỗi truyền vào có phải là DateTime
        /// </summary>
        /// <param name="text">string</param>
        /// <returns>DateTime</returns>
        public static bool IsDate(string text)
        {

            DateTime result;
            return DateTime.TryParse(text, out result);
        }

        // sinh so ngau nhien
        public static string GenerateRandomCode()
        {
            // For generating random numbers.
            Random random = new Random();
            string s = "";
            for (int i = 0; i < 4; i++)
                s = String.Concat(s, random.Next(10).ToString());
            return s;
        }

        public static int CheckDateTime(DateTime startDate, DateTime endDate)
        {
            int delta;
            TimeSpan ts = endDate.Subtract(startDate);
            delta = ts.Days;
            return delta;
        }

        private const string MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
         + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				    [0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
         + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				    [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
         + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

        /// <summary>
        /// CheckEMail
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool ValidEmail(string email)
        {
            return email != null && Regex.IsMatch(email, MatchEmailPattern);
        }

        /// <summary>
        /// Chuyển ngày tháng thành dạng dd/MM/yyy: 23:59
        /// </summary>
        /// <param name="datetimeValue">Ngày tháng đầu vào</param>
        /// <returns>DateTime</returns>
        public static DateTime CorrectToDateTime(DateTime datetimeValue)
        {
            DateTime dTemp;
            int iHour, iMinu, iSec, Oper;

            iHour = datetimeValue.Hour;
            iMinu = datetimeValue.Minute;
            iSec = datetimeValue.Second;
            Oper = -1;

            dTemp = datetimeValue.AddHours(Oper * iHour).AddMinutes(Oper * iMinu).AddSeconds(Oper * iSec);
            return dTemp.AddHours(24).AddSeconds(Oper);
        }

        public static void InitCombobox(DropDownList drpCombobox, object objValue, object oSource, string fieldDisPlay, string fieldValue, bool addNewRow = false, string valueDisplay = null)
        {
            if (oSource == null) return;

            drpCombobox.DataSource = oSource;
            drpCombobox.DataTextField = fieldDisPlay;
            drpCombobox.DataValueField = fieldValue;
            drpCombobox.DataBind();

            if (objValue != null)
            {
                drpCombobox.SelectedValue = objValue.ToString();
            }
        }

        public static void InitComboboxYear(DropDownList drpYear)
        {
            var tbl = new DataTable();
            var col = new DataColumn("Year");
            col.DataType = typeof(System.Int32);
            tbl.Columns.Add(col);
            for (int i = DateTime.Now.Year - 10; i < DateTime.Now.Year + 10; i++)
            {
                DataRow row = tbl.NewRow();
                row[0] = i;
                tbl.Rows.Add(row);
            }
            drpYear.DataTextField = "Year";
            drpYear.DataValueField = "Year";
            drpYear.DataSource = tbl;
            drpYear.SelectedValue = DateTime.Now.Year.ToString();

        }

        public static void InitComboboxMonth(DropDownList drpMonth)
        {
            DataTable tbl = new DataTable();
            DataColumn col = new DataColumn("Month");
            col.DataType = typeof(System.Int32);
            tbl.Columns.Add(col);
            for (int i = 1; i <= 12; i++)
            {
                DataRow row = tbl.NewRow();
                row[0] = i;
                tbl.Rows.Add(row);
            }
            drpMonth.DataTextField = "Month";
            drpMonth.DataValueField = "Month";
            drpMonth.DataSource = tbl;
            drpMonth.SelectedValue = DateTime.Now.Month.ToString();

        }

        public static bool IsNullOrWhiteSpace(string value)
        {
            if (value == null) return true;
            value = value.Trim();
            return string.IsNullOrEmpty(value);
        }

        public static void GetControlContent(string controlLocation, System.Web.UI.WebControls.PlaceHolder hl)
        {
            var page = new Page();

            if (!Utilities.IsNullOrWhiteSpace(controlLocation))
            {
                var userControl = page.LoadControl(controlLocation);

                hl.Controls.Add(userControl);
            }
        }

        public static string ControlUrl()
        {
            try
            {
                return ApplicationPath + "Control/";
            }
            catch { return ""; }
        }

        public static void BuildCategoryTree(ComponentArt.Web.UI.TreeView tree, string  _strCondition)
        {
            var strSQL = string.Format("exec tblCategory_GetAllByCondition '{0}'", _strCondition);
            var ds = DAL.GetDataSet(strSQL);

            var rootNode = CreateNode("--Lựa chọn danh mục--", "0", "../images/lines/folders.gif", true);
            tree.Nodes.Clear();
            tree.Nodes.Add(rootNode);

            foreach (DataRow dbRow in ds.Tables[0].Rows)
            {
                var newNode = CreateNode(dbRow["categoryName"].ToString(), dbRow["categoryId"].ToString(),
                                         "../images/lines/folders.gif", true);
                rootNode.Nodes.Add(newNode);
                var sql2 = string.Format("exec tblCategory_GetAllByCondition '{0}'",
                                         " AND parentId= " + Int32.Parse(dbRow["categoryId"].ToString()) +
                                         " AND status=1");
                var ds2 = DAL.GetDataSet(sql2);
                BuildSubTree(ds2.Tables[0], newNode);
            }

        }

        private static void BuildSubTree(DataTable dbTable, TreeViewNode node)
        {
            foreach (DataRow childRow in dbTable.Rows)
            {
                var childNode = CreateNode(childRow["categoryName"].ToString(),
                                           childRow["categoryId"].ToString(), "../images/lines/folder.gif",
                                           false);
                node.Nodes.Add(childNode);
                var sql3 = string.Format("exec tblCategory_GetAllByCondition '{0}'",
                                         " AND parentId= " + Int32.Parse(childRow["categoryId"].ToString()) +
                                         " AND status=1");
                var ds3 = DAL.GetDataSet(sql3);
                BuildSubTree(ds3.Tables[0], childNode);
            }
        }

        private static TreeViewNode CreateNode(string text, string value, string imageurl, bool expanded)
        {
            var node = new TreeViewNode { Text = text, Value = value, ImageUrl = imageurl, Expanded = expanded };
            return node;
        }

        public static string AttachJavascript(string Folder, string javascriptFile)
        {
            var str = UrlJavaScript() + Folder + "/" + javascriptFile;
            return ("<script type=\"text/javascript\" src=\"" + str + "\"></script>\r\n");
        }

    }

}